package jsfsession;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class AutorizaListener implements PhaseListener {

	private static final long serialVersionUID = 1L;

	public AutorizaListener() {

	}

	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext contexto = event.getFacesContext();
		String paginaAtual = contexto.getViewRoot().getViewId();
		boolean isLoginPage = paginaAtual.lastIndexOf("/login.xhtml") > -1;
		HttpSession sessao = (HttpSession) contexto.getExternalContext()
				.getSession(false);
		String usuario = (String) sessao.getAttribute("usuarioAutenticado");
		if ((!isLoginPage && usuario == null)
				|| (!isLoginPage && usuario.equals(""))) {
			NavigationHandler nh = contexto.getApplication()
					.getNavigationHandler();
			nh.handleNavigation(contexto, null, "error");
		} else if (isLoginPage && usuario != null) {
			NavigationHandler nh = contexto.getApplication()
					.getNavigationHandler();
			nh.handleNavigation(contexto, null, "success");
		}
	}

	public void beforePhase(PhaseEvent event) {

	}

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
}